package controllers

import (
	"minicommit/internal/datacommit"
	"strings"
	"sync"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"github.com/gofiber/fiber/v2"
)

var isWork = false
var mu sync.Mutex

func NewDataCommit(c *fiber.Ctx) error {

	if isWork == true {
		c.Status(fiber.ErrConflict.Code)
		return c.JSON(fiber.Map{
			"message": "in work",
			"success": "NO",
		})
	}
	mu.Lock()
	isWork = true
	mu.Unlock()

	var data datacommit.Commit
	workDir := c.Locals("workDir").(string)
	token := c.Locals("BotToken").(string)
	id := c.Locals("AdminID").(int64)
	err := c.BodyParser(&data)
	data.BranchName = c.Locals("BranchName").(string)

	if err != nil {
		c.Status(fiber.ErrBadRequest.Code)
		msg := err.Error()
		go sendError(msg, token, id)
		mu.Lock()
		isWork = false
		mu.Unlock()
		return c.JSON(fiber.Map{
			"message": msg,
			"success": "NO",
		})
	}

	err = data.CreateCommit(workDir)

	if err != nil {
		if strings.Contains(err.Error(), "no changes added") == false {
			c.Status(fiber.StatusInternalServerError)
			msg := err.Error()
			go sendError(msg, token, id)
			mu.Lock()
			isWork = false
			mu.Unlock()
			return c.JSON(fiber.Map{
				"message": msg,
				"success": "NO",
			})
		}
	}
	isWork = false
	return c.JSON(fiber.Map{
		"success": "OK",
	})
}

func sendError(msg, token string, id int64) {
	bot, err := tgbotapi.NewBotAPI(token)
	if err != nil {
		return
	}
	mu.Lock()
	isWork = false
	mu.Unlock()

	tgmsg := tgbotapi.NewMessage(id, "Commit error: "+msg)
	bot.Send(tgmsg)
}

func CheckJob(c *fiber.Ctx) error {
	return c.JSON(fiber.Map{
		"success": "OK",
	})
}
